package com.atguigu.gulimall.order.config;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @create: 2024/9/10
 * @author: gyhe10
 * @description:
 **/

@Configuration
public class MyRabbitConfig {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 定制 RabbitTemplate
     */
    @PostConstruct// 在构造器方法执行之后执行
    public void initRabbitTemplate() {
        /**
         * 消息是否抵达 RabbitMQ 服务器的确认回调
         * 只要消息抵达 RabbitMQ 服务器，ack = true
         * correlationData：当前消息的唯一关联数据（消息的唯一 id）
         * ack：消息收到 ack = true， 否则 false
         * cause：失败的原因
         */
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println("confirm...correlationData = " + correlationData + ", ack = " + ack + ", cause = " + cause);
        });

        /**
         * 消息是否成功从 RabbitMQ 服务器投递到 Queue 中，投递失败，触发该回调
         * message：投递失败的消息详细信息
         * replyCode：回复的状态码
         * replyText：回复的文本内容
         * exchange：当前消息要投递到哪个交换机
         * routingKey：当前消息使用的路由键
         */
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            System.out.println("return...message = " + message + ", replyCode = " + replyCode + ", replyText = " + replyText + ", exchange = " + exchange + ", routingKey = " + routingKey);
        });
    }


}
